#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <pthread.h>
#include "TM1637.h"

#define R 13
#define G 19
#define B 26
#define BUTTON 4

void button_check(int* flag)
{
    while(digitalRead(BUTTON)==LOW);
    *flag = 0;
}

int main()
{
    if(wiringPiSetupGpio()<0)
    {
        printf("初始化引脚失败\n");
        return 1;
    }

    pinMode(DIO,OUTPUT);
    pinMode(CLK,OUTPUT);
    pinMode(G,OUTPUT);
    pinMode(BUTTON,INPUT);

    printf("请设置闹钟时间(例如 6:00):");
    int a_hour = 0;
    int a_min = 0;
    scanf("%d:%d",&a_hour,&a_min);
    
    int a_flag = 1;
    while(1)
    {
        time_t t = time(NULL);
        struct tm* lt = localtime(&t);
        int n_hour = lt->tm_hour;
        int n_minute = lt->tm_min;
        if(n_hour == 0 && n_minute == 0)
        {
            a_flag = 1;
        }

        if(n_hour == a_hour && n_minute == a_min && a_flag == 1)
        {
            pthread_t tid = 0;
            pthread_create(&tid,NULL,(void*)button_check,(void*)&a_flag);
            while(a_flag)
            {
                printf("%d\n",a_flag);
                display(n_hour/10,n_hour%10,n_minute/10,n_minute%10);
                digitalWrite(G,LOW);
                sleep(1);
                nodisplay();
                digitalWrite(G,HIGH);
                sleep(1);   
            }
        }
        else
        {   
            display(n_hour/10,n_hour%10,n_minute/10,n_minute%10);
            digitalWrite(G,LOW);
            sleep(1);
        }

    }
    return 0;
}